# coding:utf-8
import logging
import os
import time

import allure
from appium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from config.confManage import dir_manage
from utils.common.log import Log

success = "SUCCESS   "
fail = "FAIL      "
warning = "WARNING   "
error = "ERROR     "
Log()
el = None


class appiumDriver(object):
    """浏览器引擎"""

    @staticmethod
    def appiumDriver(app=None):
        t1 = time.time()
        try:
            driver = webdriver.Remote('http://localhost:4723/wd/hub', app)
            logging.info(
                "{0} 打开app, 用时 {1:.2f} 秒.".format(success, time.time() - t1)
            )
            return driver
        except Exception:
            raise


class pyappium(appiumDriver):
    def __init__(self, driver):
        self.driver = driver
        self.el = None
        # from config import APP
        # self.driver = webdriver.Remote('http://localhost:4723/wd/hub', APP)  # 调试模式

    def element_wait(self, css, sec=30):

        t1 = time.time()
        messages = '{0}秒内，未能找到元素：{1} '.format(sec, css)
        try:
            WebDriverWait(self.driver, sec, 1).until(EC.presence_of_element_located(css), messages)
            logging.debug("{0} 等待{1}元素可见, 用时{2:.2f}秒.".format(success, css, time.time() - t1))
        except:
            logging.error("{0} 等待{1}元素可见失败, 用时{2:.2f}秒.".format(fail, css, time.time() - t1))
            raise

    # ement

    def get_element(self, css):
        """获取元素"""

        t1 = time.time()
        logging.info("{0} 查找元素：{1}, 用时{2:.2f}秒.".format(success, css, time.time() - t1))
        try:
            ele = self.driver.find_element(*css)
        except:
            logging.error("{0} 查找元素{1}失败！用时{2:.2f}秒.".format(fail, css, time.time() - t1))
            raise
        else:
            return ele

    def get_elements(self, css):
        """
        Judge element positioning way, and returns the element.
        批量获取元素。
        Usage:
        driver.get_elements('id->kw')
        """

        t1 = time.time()
        logging.info("{0} 查找元素：{1}, 用时{2:.2f}秒.".format(success, css, time.time() - t1))
        try:
            ele = self.driver.find_elements(*css)
        except:
            logging.error("{0} 查找元素{1}失败！用时{2:.2f}秒.".format(fail, css, time.time() - t1))
            raise

        else:
            return ele

    def click(self, css):
        """点击"""

        t1 = time.time()
        try:
            self.element_wait(css)
            self.get_element(css).click()
            logging.info(
                "{0} 点击元素：{1}， 用时 {2:.2f} 秒.".format(success, css, time.time() - t1)
            )
            return self
        except Exception:
            logging.error(
                "{0} 未能点击元素{1}.".format(fail, css)
            )
            raise

    def quite(self):
        t1 = time.time()
        self.driver.quit()
        logging.info(
            "{0} 退出app并清除临时文件， 用时 {1:.2f} 秒.".format(success, time.time() - t1)
        )
        return self

    def take_screenshot(self):
        """截图"""
        t1 = time.time()
        date = time.strftime('%Y-%m-%d')
        file_path = dir_manage('${pro_dir}$') + dir_manage('${report_html_dir}$') + date + '/' + date
        image_path = file_path + "/image/"
        isExists = os.path.exists(file_path)
        isExists2 = os.path.exists(image_path)
        if not isExists:
            os.mkdir(file_path)
        if not isExists2:
            os.mkdir(image_path)
        date = time.strftime('%Y%m%d%H%M%S', time.localtime())
        screenname = image_path + date + ".png"
        try:
            picture_url = self.driver.get_screenshot_as_png()
            picture_path = self.driver.get_screenshot_as_file(screenname)
            if picture_path:
                allure.attach(picture_url, date)
                print('screenshot:  {0}.png'.format(date))
                logging.info(
                    "{0} 截图保存成功，地址为{1}， 用时 {2:.2f} 秒.".format(success, image_path, time.time() - t1)
                )
            else:
                logging.error("{0} 截图保存失败.".format(warning))
        except Exception:
            logging.error("截图失败!")
            raise AttributeError(
                "截图失败"
            )

    def input(self, css, text):
        """输入"""

        t1 = time.time()
        try:
            self.element_wait(css)

            self.el = self.get_element(css)
            self.el.send_keys(text)
            logging.info(
                "{0} 元素：{1}，内容：‘{2}’输入成功， 用时 {3:.2f} 秒.".format(success, css, text, time.time() - t1)
            )
            return self
        except Exception:

            logging.error(
                "{0} 元素：{1}，内容：‘{2}’输入失败， 用时 {3:.2f} 秒.".format(fail, css, text, time.time() - t1)
            )
            self.take_screenshot()
            raise

    def sleep(self, secs=5):
        """强制等待"""
        time.sleep(secs)
        logging.info(
            "{0} 等待 {1:.2f} 秒钟".format(success, secs)
        )
        return self


if __name__ == "__main__":
    from appium.webdriver.common.mobileby import MobileBy

    userAgreement = (MobileBy.XPATH, "//*[@text='同意']")
    # dr = pyappium()
    #
    # # time.sleep(3)
    # dr2.click(userAgreement)
